﻿Imports System.Runtime.CompilerServices
Imports System.IO

Module BitmapExtentions
    <Extension()> _
    Public Function CreateSquareThumb(ByVal fullSizeImg As System.Drawing.Bitmap, Optional NewSize As Integer = 250) As System.Drawing.Bitmap

        Dim myBitmapCropped As System.Drawing.Bitmap

        Dim width As Integer = fullSizeImg.Width
        Dim height As Integer = fullSizeImg.Height
        Dim dummyCallBack As New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)
        Dim x As Integer = 0
        Dim y As Integer = 0

        If width > height Then
            width = CType((width / height) * NewSize, Integer)
            height = NewSize
            x = Math.Ceiling((width - height) / 2)
        ElseIf height > width Then
            height = CType((height / width) * NewSize, Integer)
            width = NewSize
            y = Math.Ceiling((height - width) / 2)
        Else
            width = NewSize
            height = NewSize
        End If

        Using thumbNailImg As System.Drawing.Bitmap = fullSizeImg.GetThumbnailImage(width, height, dummyCallBack, IntPtr.Zero)

            myBitmapCropped = New System.Drawing.Bitmap(NewSize, NewSize)
            Dim myGraphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(myBitmapCropped)

            myGraphic.DrawImage(thumbNailImg, New System.Drawing.Rectangle(0, 0, myBitmapCropped.Width, myBitmapCropped.Height), x, y, myBitmapCropped.Width, myBitmapCropped.Height, System.Drawing.GraphicsUnit.Pixel)
            myGraphic.Dispose()

        End Using

        Return myBitmapCropped
    End Function
    Private Function ThumbnailCallback() As Boolean
        Return False
    End Function

End Module
